//
//  PageManager.swift
//  FlameB
//
//  Created by 连俊 on 2020/7/30.
//  Copyright © 2020 连俊. All rights reserved.
//

import UIKit

class PageManager: NSObject {
    static let shared = PageManager()
    
    var tabbarVC: BaseTabBarController?
    
    override init() {
        super.init()
    }
    
    func chooseRootViewController(_ window: UIWindow?) {
        guard let _ = User.loadFromKC() else {
            ///未登录
            chooseLogin(window)
            return
        }
        //不需要登录
        tabbarVC = BaseTabBarController()
        let nav = BaseNavigationViewController.init(rootViewController: tabbarVC!)
        UIViewController.setKeyWindowRootViewController(root: nav, animated: true)
    }
    
    func chooseLogin(_ window: UIWindow?) {
        let vc = PageManager.shared.topViewController
        if vc is LoginViewController {
            return
        }
        let login = LoginViewController()
        window?.rootViewController = login
    }
    
    var topViewController: UIViewController? {
        var resultVC: UIViewController?
        resultVC = _topViewController(UIApplication.shared.keyWindow?.rootViewController)
        while ((resultVC?.presentedViewController) != nil) {
            resultVC = _topViewController(resultVC?.presentedViewController)
        }
        return resultVC
    }
    
    func _topViewController(_ vc: UIViewController?) -> UIViewController? {
        if (vc is UINavigationController) {
            return _topViewController((vc as? UINavigationController)?.topViewController)
        } else if (vc is UITabBarController) {
            return _topViewController((vc as? UITabBarController)?.selectedViewController)
        } else {
            return vc
        }
    }
}
